import { Component, OnInit } from '@angular/core';
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../../util/page-subject";
import {ValidRateService} from "./valid-rate.service";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../../util/response-util";
import {MsgResult} from "../../../../models/msg-result";
import {MsgConstants} from "../../../../constants/constants";
import {TableUtil} from "../../../../util/table-util";

declare var $;
declare var moment;

@Component({
  selector: 'app-valid-rate',
  templateUrl: './valid-rate.component.html',
  styleUrls: ['./valid-rate.component.css']
})
export class ValidRateComponent implements OnInit {
  config;changeObj;initObj;table;
  regionCodeType:any;
  nationalSite:Array<any>=[];
  provinceSite:Array<any>=[];
  smallSite:Array<any>=[];
  constructor(
    private pageSubject : PageSubject,
    private ValidRateService : ValidRateService,
    private responseUtil :ResponseUtil,
    private dialogService: OneDialogService,
    private tableUtil:TableUtil,
  ) { }

  ngOnInit() {
    this.pushPage();
    this.getRegionList();
    this.initTime();
    this.siteButtonData();
    $(".one-data-loadState").show();
  }

  //面包屑导航
  pushPage() {
    let path = new Path("统计报表", "");
    this.pageSubject.pushPage("有效率", "", path);
  }

  //站点按钮数据
  siteButtonData(){
    this.ValidRateService.getUserSiteData().subscribe(
      result => this.responseUtil.success(result,this.siteButtonDataResult),
      message => this.responseUtil.error(message)
    );
  }
  private siteButtonDataResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.siteButtonDataDataTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  //站点按钮
  siteButtonDataDataTree(data){
    let siteHtml = "";
    let localSite = [
      {"name":"nationalSite","type":"national","chinese":"国控站"},
      {"name":"provinceSite","type":"province","chinese":"省控站"},
      {"name":"smallAirSite","type":"smallAir","chinese":"微型站"}
    ];
    $.each(localSite,function (j,siteList) {
      $.each(data,function (i,list) {
        if(list==siteList.name){
          siteHtml+='<div class="btn btn-default" id="'+siteList.name+'" data-type="'+siteList.type+'">'+siteList.chinese+'</div>';
        }
      });
    });
    if(siteHtml){
      $(".user_site_button").html(siteHtml);
      $(".user_site_button").find(".btn:first").addClass("active");
      this.initBtnStyle();
      this.initBtnEvent();
      this.initObj = {"startTime":moment().subtract(1,"d").format("YYYY-MM-DD HH")+":00:00","endTime":moment().format("YYYY-MM-DD HH")+":00:00","siteCode":""}
      this.tableContentData(this.initObj);
    }else{
      $(".one-data-loadState").hide();
      $(".user_zong").html("暂无数据");
    }

  };

  //选择城市
  getRegionList(){
    this.ValidRateService.getregionCodeData().subscribe(
      result => this.responseUtil.success(result,this.getregionCodeDataResult),
      message => this.responseUtil.error(message)
    );
  }
  private getregionCodeDataResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dropDownCityData(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  //城市列表
  dropDownCityData(data){
    let dataHtml = "";
    $.each(data, function (i, list) {
      dataHtml += '<li id="' + list.regionCode + '">' + list.regionName + '</li>';
    });
    $(".user_dropdown-menu_city ul").html(dataHtml);
    $(".user_dropdown-menu_city ul li").click(function (e) {
      $(".upload_city").val($(e.target).html());
      let siteId = $(e.target).attr("id");
      $(".user_dropdown-menu_city").hide();
      this.regionCodeType =siteId;
      console.log(this.regionCodeType);
      this.getRegionListData();
    }.bind(this))
  }

  //站点列表数据
  getRegionListData(){
    this.ValidRateService.getRegionListData(this.regionCodeType).subscribe(
      result => this.responseUtil.success(result,this.getRegionListDataResult),
      message => this.responseUtil.error(message)
    );
  }
  private getRegionListDataResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.getRegionListDataTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  //站点列表
  getRegionListDataTree(data){
    this.nationalSite=[];
    this.provinceSite=[];
    this.smallSite=[];
    $.each(data,function (i,dropDatas) {
      if(dropDatas.siteTypeCode=="001"){
        this.nationalSite.push({"siteCode":dropDatas.siteCode,"siteName":dropDatas.siteName});
      }else if(dropDatas.siteTypeCode=="002"){
        this.provinceSite.push({"siteCode":dropDatas.siteCode,"siteName":dropDatas.siteName});
      }else if(dropDatas.siteTypeCode=="004"){
        this.smallSite.push({"siteCode":dropDatas.siteCode,"siteName":dropDatas.siteName});
      }
    }.bind(this));



  }

  //表格数据
  tableContentData(obj){
    this.ValidRateService.getUploadRateData(obj).subscribe(
      result => this.responseUtil.success(result,this.tableContentDataResult),
      message => this.responseUtil.error(message)
    );
  }
  private tableContentDataResult = (result: MsgResult) =>{
    $(".one-data-loadState").hide();
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.tableContent(result.data.dataList);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  //表格
  tableContent(datas){
    $(".one-table-area").html('<table class="table table-striped" id="uploadRateTable"></table>');
    this.table = this.tableUtil.load("uploadRateTable",{
      columns: [
        [{
          field: 'regionName',
          title: '城市名称',
          rowspan: 2,
          valign:"middle",
          halign:"center",
          width:90
        }, {
          field: 'siteName',
          title: '监测站点名称',
          rowspan: 2,
          valign:"middle",
          halign:"center",
          width:90
        },
          {
            field: '',
            title: 'PM10',
            colspan: 3,
            width:150,
            align:"center",
            halign:"center"
          },{
          field: '',
          title: 'PM2.5',
          colspan: 3,
          width:150,
          align:"center",
          halign:"center"
        },{
          field: '',
          title: 'SO<sub>2</sub>',
          colspan: 3,
          width:150,
          align:"center",
          halign:"center"
        },{
          field: '',
          title: 'NO<sub>2</sub>',
          colspan: 3,
          width:150,
          align:"center",
          halign:"center"
        },{
          field: '',
          title: 'O<sub>3</sub>',
          colspan: 3,
          width:150,
          align:"center",
          halign:"center"
        },{
          field: '',
          title: 'CO',
          colspan: 3,
          width:150,
          align:"center",
          halign:"center"
        }],[
          {
            field: 'pm10.shouldNum',
            title: '应传数',
            width:50,
            align:"right",
            halign:"center"
          },{
            field: 'pm10.validNum',
            title: '实传数',
            width:50,
            align:"right",
            halign:"center"
          },{
            field: 'pm10.validRate',
            title: '上传率(%)',
            width:50,
            align:"right",
            halign:"center"
          },{
            field: 'pm2_5.shouldNum',
            title: '应传数',
            width:50,
            align:"right",
            halign:"center"
          },{
            field: 'pm2_5.validNum',
            title: '实传数',
            width:50,
            align:"right",
            halign:"center"
          },{
            field: 'pm2_5.validRate',
            title: '上传率(%)',
            width:50,
            align:"right",
            halign:"center"
          },{
            field: 'so2.shouldNum',
            title: '应传数',
            width:50,
            align:"right",
            halign:"center"
          },{
            field: 'so2.validNum',
            title: '实传数',
            width:50,
            align:"right",
            halign:"center"
          },{
            field: 'so2.validRate',
            title: '上传率(%)',
            width:50,
            align:"right",
            halign:"center"
          },{
            field: 'no2.shouldNum',
            title: '应传数',
            width:50,
            align:"right",
            halign:"center"
          },{
            field: 'no2.validNum',
            title: '实传数',
            width:50,
            align:"right",
            halign:"center"
          },{
            field: 'no2.validRate',
            title: '上传率(%)',
            width:50,
            align:"right",
            halign:"center"
          },{
            field: 'o3.shouldNum',
            title: '应传数',
            width:50,
            align:"right",
            halign:"center"
          },{
            field: 'o3.validNum',
            title: '实传数',
            width:50,
            align:"right",
            halign:"center"
          },{
            field: 'o3.validRate',
            title: '上传率(%)',
            width:50,
            align:"right",
            halign:"center"
          },{
            field: 'co.shouldNum',
            title: '应传数',
            width:50,
            align:"right",
            halign:"center"
          },{
            field: 'co.validNum',
            title: '实传数',
            width:50,
            align:"right",
            halign:"center"
          },{
            field: 'co.validRate',
            title: '上传率(%)',
            width:50,
            align:"right",
            halign:"center"
          }]
      ],
      data:datas,
      pagination :true,
      paginationLoop: false,
      striped :true,
      paginationPreText : "上一页",
      paginationNextText :"下一页",
      undefinedText : " ",
      height:$(window.innerHeight)[0]-240,
      pageSize:15,
      pageList :[10,15,20]
    });
  };

  //按钮样式
  initBtnStyle(){
    //改变input样式
    $('input').iCheck({
      checkboxClass: 'icheckbox_minimal-green',
      radioClass: 'iradio_minimal-green',
      increaseArea: '20%' // optional
    });
    //按钮点击事件
    $(".btn-group .btn:not(.btn-disabled)").click(function(){
      $(this).addClass("active").siblings(".active").removeClass("active");
    });

    //点击站点列表
    $(".dropdown").click(function(){
      $(this).find(".dropdown-menu").show();
    }).mouseleave(function(){
      $(this).find(".dropdown-menu").hide();
    });


    //点击站点列表中的删除图标
    $(".one-inline-container").on("click",".btn>.glyphicon-remove",function(){
      $(this).parent().remove();
      if($(".one-inline-container>.btn").length<5){
        $('.list-inline input').iCheck('enable');
      }else{
        $('.list-inline .icheckbox_minimal-green:not(.checked) input').iCheck('disable');
      }
      var btnId = $(this).parent().attr("id");
      $(".dropdown-menu label").each(function(){
        var  id = $(this).find("input").attr("id");
        if( btnId == id){
          $(this).find("input").iCheck('uncheck');
        }
      });
    });
  }

//点击事件
  initBtnEvent(){
    $(".glyphicon-remove").click(function (event) {
      event=event?event:window.event;
      event.stopPropagation();
    })
    //点击站点类型
    $(".dropdown-menu>.one-btn-data-type").on("click",".btn",function(){
      $(this).addClass("active").siblings(".active").removeClass("active");
      var id = $(this).data("type");
      $("#"+id).show().siblings(".list-inline").hide();
    });

    //查询站点
    $("#search-site").bind("input propertychange",function () {
      let searchSiteVal = $("#search-site").val();
      if(searchSiteVal){
        $(".dropdown-menu label").each(function(){
          var text = $(this).text();
          if(text.indexOf(searchSiteVal)!=-1){
            $(this).parent().show();
          }else{
            $(this).parent().hide();
          }
        })
      }else{
        $(".dropdown-menu label").parent().show();
      }
    })
  }

  //获取改变数据
  changeData(){
    let siteCode;
    let checkedSiteListObj = [];
    $(".one-inline-container>.btn").each(function () {
      var id = $(this).attr("id");
      checkedSiteListObj.push(id);
    });
    siteCode = checkedSiteListObj.join(",");
    let startTime =  $.trim($("#uploadRateDate").val().split("至")[0]);
    let endTime =  $.trim($("#uploadRateDate").val().split("至")[1]);
    startTime+=startTime.split(" ").length==1?" 00:00:00":":00";
    endTime+=endTime.split(" ").length==1?" 00:00:00":":00";
    this.changeObj = {"siteCode":siteCode,"startTime":startTime,"endTime":endTime }
    $(".one-data-loadState").show();
    this.tableContentData(this.changeObj);
  }

  //初始化时间插件
  initTime(){
    let timeData = moment().format("YYYY-MM-DD HH")+":00"
    this.config = {
      timePicker:true,
      timePickerIncrement:5,
      timePicker24Hour:true,
      parentEl:$(".wrapper"),
      locale:{
        format:"YYYY-MM-DD HH:00",
        separator: " 至 ",
        applyLabel : '确定',
        cancelLabel : '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek:["日","一","二","三","四","五","六"],
        monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
        firstDay:1
      },
      startDate: moment().subtract(1,"d").format("YYYY-MM-DD HH")+":00",
      endDate: timeData,
      maxDate: timeData
    };
    $("#uploadRateDate").daterangepicker(this.config);

  }

  inputClick(siteCode,name,even){
    let aa=$(even.target).is(":checked");
    if(aa){
      $(".one-inline-container").append('<div class="btn btn-success" id='+siteCode+'>'+name+' <i class="glyphicon glyphicon-remove"></i></div>');
    }else{
      $(".one-inline-container").find("#"+siteCode).remove();
    }
  }


}
